package com.toune.dltools.ui

import android.app.Activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProviders
import com.jaeger.library.StatusBarUtil
import com.qmuiteam.qmui.arch.QMUIFragment
import com.tamsiree.rxkit.RxActivityTool
import java.lang.reflect.ParameterizedType

/**
 * @Author Dong Lei
 * @Date 2020/12/7 0007-上午 8:58
 * @Info 描述：
 */
abstract class DLBaseFragment<V : DLBaseViewModel> : Fragment() {

    lateinit var mRootView: View
    lateinit var mViewModel: V
    abstract val layout: Int
    var isLoaded = false //控制是否执行懒加载

    /**
     * 创建一个Class的对象来获取泛型的class
     */
    private var clz: Class<V>? = null

    open fun getClz(): Class<V>? {
        if (clz == null) {
            clz =
                (this.javaClass.genericSuperclass as ParameterizedType?)!!.actualTypeArguments[0] as Class<V>?
        }
        return clz
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mViewModel = ViewModelProviders.of(this).get(getClz()!!)
        mRootView = View.inflate(context, layout, null)
        return mRootView
    }

    override fun onResume() {
        super.onResume()
        judgeLazyInit()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        userVisibleHint = !hidden
        judgeLazyInit()
    }

    private fun judgeLazyInit() {
        if (!isLoaded && !isHidden) {
            lazyInit()
            isLoaded = true
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        isLoaded = false
    }


    //懒加载方法
    abstract fun lazyInit()

    fun showLoading() {
        (activity as DLBaseActivity<*>).showLoading()
    }

    fun hideLoading() {
        (activity as DLBaseActivity<*>).hideLoading()
    }

    /**
     * 本Fragment进行的跳转
     * @param clazz Class<Any>
     */
    fun startToActivity(clazz: Class<out Activity>) {
        RxActivityTool.skipActivity(requireContext(), clazz)
    }

    /**
     * 本Fragment进行的带参数跳转
     * @param clazz Class<Any>
     * @param bundle Bundle
     */
    fun startToActivity(clazz: Class<out Activity>, bundle: Bundle) {
        RxActivityTool.skipActivity(requireContext(), clazz, bundle)
    }

    /**
     * 添加其他的model
     */
    inline fun <reified T : DLBaseViewModel> addViewModel(): T {
        return ViewModelProviders.of(this).get(T::class.java)
    }

}